package com.server.utils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class GlobalUtils {
    // 对Map类型的集合进行排序
    public static List<Map<String,Object>> mapListSorted(List<Map<String,Object>> list, String key){
        // 采用 匿名内部类的 方式，自定义排序
        Collections.sort(list,new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                String s1 = ((Map<String,Object>)o1).get(key).toString();
                String s2 = ((Map<String,Object>)o2).get(key).toString();
                return s1.compareTo(s2) ;
            }
        });
        return list;
    }


//    // 对 StRsvr 类型的集合进行排序
//    public static List<StRsvr> tableListSortedForTime(List<StRsvr> list){
//        // 采用 匿名内部类的 方式，自定义排序
//        Collections.sort(list,new Comparator() {
//            @Override
//            public int compare(Object o1, Object o2) {
//                Date s1 = ((StRsvr)o1).getTm();
//                Date s2 = ((StRsvr)o2).getTm();
//                return s1.compareTo(s2) ;
//            }
//        });
//        return list;
//    }

    // 一、日期操作
    // 直接日期添加天数
    // 日期添加小时
    public static Date getStrictDateAddHour(Date date0,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.HOUR_OF_DAY, count);
            return calendar.getTime();
        }catch (Exception e){
            return null;
        }
    }

    // 日期添加天数
    public static Date getStrictDateAddDay(Date date0,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.DAY_OF_MONTH, count);
            return calendar.getTime();
        }catch (Exception e){
            return null;
        }
    }

    // 日期添加月份
    public static Date getStrictDateAddMonth(Date date0,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.MONTH, count);
            return calendar.getTime();
        }catch (Exception e){
            return null;
        }
    }
    // 日期添加年份
    public static Date getStrictDateAddYear(Date date0,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.YEAR, count);
            return calendar.getTime();
        }catch (Exception e){
            return null;
        }
    }


    // 二、字符串操作
    // 字符串转换为日期
    public static Date transformStringToDate(String str){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse( str );
        }catch (Exception e){
            return new Date();
        }
    }

    // 日期转换为字符串
    public static String transformDateToString(Date date){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }catch (Exception e){
            return "";
        }
    }

    // 日期添加分钟
    public static String getDateAddMinute(String date,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date0 = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.MINUTE, count);
            String date1 = sdf.format(calendar.getTime());
            return date1;
        }catch (Exception e){
            return "";
        }
    }

    // 日期添加小时
    public static String getDateAddHour(String date,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date0 = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.HOUR_OF_DAY, count);
            String date1 = sdf.format(calendar.getTime());
            return date1;
        }catch (Exception e){
            return "";
        }
    }

    // 日期添加天数
    public static String getDateAddDay(String date,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date0 = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.DAY_OF_MONTH, count);
            String date1 = sdf.format(calendar.getTime());
            return date1;
        }catch (Exception e){
            return "";
        }
    }

    // 日期添加月份
    public static String getDateAddMonth(String date,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date0 = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.MONTH, count);
            String date1 = sdf.format(calendar.getTime());
            return date1;
        }catch (Exception e){
            return "";
        }
    }
    // 日期添加年份
    public static String getDateAddYear(String date,int count){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date0 = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date0);
            calendar.add(Calendar.YEAR, count);
            return sdf.format(calendar.getTime());
        }catch (Exception e){
            return "";

        }
    }

    // 获取当前日期时间
    public static String getCurrentTime(){
        return transformDateToString(new Date());
    }


    // 判断日期是否超过当日的日期 (是超过返回当前时间，不是则null)
    public static String getCompareDate(String date){
        String current = transformDateToString(new Date());
        if(current.compareTo(date)< 0){
            return current;
        }else{
            return null;
        }
    }

    // 判断日期是否包含在当日的日期内
    public static String getContainDate(String date){
        String current = transformDateToString(new Date());
        if(current.compareTo(date)> 0){
            // 2022-10-01 08:10:00
            String hourStr = current.substring(11,13);
            int hour = Integer.parseInt(hourStr);
            String before = "";
            if(hour > 8){
                 before = current.substring(0,10) + " 08:00:00";
            }else{
                 before = getDateAddDay(current.substring(0,10) + " 08:00:00",-1);
            }
            if(before.compareTo(date)> 0){
                return "pass";
            }else{
                return before;
            }
        }else{
            return "null";
        }
    }

    // 获取今日早8时的日期
    public static String getStartDate(){
        String current = transformDateToString(new Date());
        int hour = Integer.parseInt(current.substring(11,13));
        if(hour >= 8){
            return current.substring(0,10) + " 08:00:00";
        }else{
            return getDateAddDay(current.substring(0,10) + " 08:00:00",-1);
        }
    }
    //生成指定日期范围间的随机数据
    public static Date randomDate(String startTime, String endTime) throws ParseException {
        Date start = transformStringToDate(startTime);
        Date end = transformStringToDate(endTime);

        long startMillis = start.getTime();
        long diff = end.getTime() - startMillis;
        long randomMillis = startMillis + (long) (Math.random() * diff);

        return new Date(randomMillis);
    }

    // 实现"2024-07-23 12:34:56"->"2024-07-23 12:35:00"
    public static Date aroundDateToFiveMinute(Date inputDate) {
        // 使用Calendar处理日期时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);

        int minutes = calendar.get(Calendar.MINUTE);
        int roundedMinutes;
        // 向下取整，分钟的个位数到0,5
        if (minutes % 10 < 5) {// 获取个位数
            roundedMinutes=minutes/10*10; // 去除个位数
        } else {
            roundedMinutes=minutes/10*10+5; // 去除个位数然后加5
        }

        int seconds = calendar.get(Calendar.SECOND);
        int roundedSeconds;
        // 向下取整，秒钟的个位数到0,5
        if (seconds % 10 < 5) {// 获取个位数
            roundedSeconds=minutes/10*10; // 去除个位数
        } else {
            roundedSeconds=minutes/10*10+5; // 去除个位数然后加5
        }
        // 设置四舍五入后的分钟数和秒数为00
        calendar.set(Calendar.MINUTE, roundedMinutes);
        calendar.set(Calendar.SECOND, roundedSeconds);
        calendar.set(Calendar.MILLISECOND, 0);
        // 由于Calendar实例的getTime()方法返回的是Date对象，直接返回
        return calendar.getTime();
    }

    // 实现"2024-07-23 12:34:56"->"2024-07-23 12:35:00"
    public static String aroundDateToFiveMinute(String inputDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = transformStringToDate(inputDate);
        // 使用SimpleDateFormat格式化返回结果
        return sdf.format(aroundDateToFiveMinute(date));
    }
    // 三、专属功能操作
    public static String getLeveDay(String date){
        try{
            String prefix = date.substring(0,10);
            String afterfix = " 08:00:00";
            int hour = Integer.parseInt(date.substring(11,13));
            if((hour >= 8 && hour <= 23) ){
                return prefix + afterfix;
            }else {
                //hour >= 0 && hour <= 7
                return getDateAddDay(prefix + afterfix,-1);
            }
        }catch (Exception e){
            return "";
        }
    }
    public static Integer getParseCurrent(String tm){
        try{
            // "07:35:00";
            int hour  = Integer.parseInt(tm.substring(0,2));
            int minute  = Integer.parseInt(tm.substring(3,5));
            int index = 1;
            if(hour >= 8){
                index = (hour - 8) * 12 + (minute / 5) + 1;
            }else{
                index = (hour + 16) * 12 + (minute / 5) + 1;
            }
            return index;
        }catch (Exception e){
            return 10000;
        }
    }

    public static double getNumDeconvert(double a){
        DecimalFormat df   = new DecimalFormat("######0.0");
        DecimalFormat df2   = new DecimalFormat("######0");

        double b=0.0;

        double a1= Double.parseDouble(df.format(a));
        double a2= Double.parseDouble(df2.format(a));
        double a3=a2+0.5;
        if (a<a3){
            b=a2;
        }else if (a == a3){
            b=a3;
        }else if(a>a3){
            b=a2+1;
        }
        return b;

    }

    // 四、日期格式的操作
    public static int getDateFormat(Date date, String type){
        try{
            // yyyy-MM-dd HH:mm:ss
            String t = "";
            if(type.equals("year")){
                t = "yyyy";
            }else if(type.equals("month")){
                t = "MM";
            }else if(type.equals("day")){
                t = "dd";
            }else if(type.equals("hour")){
                t = "HH";
            }else if(type.equals("minute")){
                t = "mm";
            }else if(type.equals("second")){
                t = "ss";
            }
            DateFormat df = new SimpleDateFormat(t);
            return Integer.parseInt(df.format(date));
        }catch (Exception e){
            System.out.println("获取日期错误"+e.getMessage());
            return -1;
        }
    }

    // 数据格式化
    public static double getDoubleFormat(Double data, int len){
        try{
            double step = Math.pow(10,len);
            return Math.round(data*step)/step;
        }catch (Exception e){
            System.out.println("获取格式化数据错误"+e.getMessage());
            return -1;
        }
    }
    // 获取平滑数据(decade为0.02)
    public static double getSlideFormat(Double preData, Double curData, Double decade ){
        try{
            if (curData == null){
                return preData;
            }
            if(preData== null || getDoubleFormat(preData + decade,2) < curData || getDoubleFormat(preData - decade,2) > curData ){
                return curData;
            }
            return preData;
        }catch (Exception e){
            System.out.println("获取格式化数据错误"+e.getMessage());
            return curData;
        }
    }

    // 获取有效数据，
    // 如果非法，则返回0
    public static double getUseNum(Double origin){
        try{
            if(origin != null && !Double.isNaN(origin)){
                return origin;
            }
            return 0d;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return 0d;
        }
    }
    // 如果非法，则返回0
    public static Double getTimeData(String origin, double data){
        try{
            if(origin != null ){
                return data;
            }
            return null;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return null;
        }
    }
    // 获取添加数据，
    // 如果非法，则返回0
    public static int getAddCount(Double origin,int originCount){
        try{
            if(origin != null && !Double.isNaN(origin)){
                return originCount+1;
            }
            return originCount;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return originCount;
        }
    }

    // 获取判断，
    // 如果非法，则返回0
    public static boolean getEqualDouble(Double origin,Double data, String tag){
        try{
            if(origin != null && data != null){
                switch(tag){
                    case ">":
                        return origin > data;
                    case "<":
                        return origin < data;
                    case "=":
                        return origin.equals(data);
                    case ">=":
                        return origin >= data;
                    case "<=":
                        return origin <= data;
                    case "!=":
                        return !origin.equals(data);
                }
//                if(tag.equals(">")){
//                    return origin > data;
//                }
//                if(tag.equals("<")){
//                    return origin < data;
//                }
//                if(tag.equals("=")){
//                    return origin.equals(data);
//                }
//                if(tag.equals(">=")){
//                    return origin >= data;
//                }
//                if(tag.equals("<=")){
//                    return origin <= data;
//                }
//                if(tag.equals("!=")){
//                    return !origin.equals(data);
//                }
                return false;
            }
            return false;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return false;
        }
    }

    // 获取判断，
    // 如果非法，则返回0
    public static boolean getEqualString(String origin,String data, String tag){
        try{
            if(origin != null && data != null){
                switch(tag){
                    case ">":
                        return origin.compareTo(data) > 0;
                    case "<":
                        return origin.compareTo(data) < 0;
                    case "=":
                        return origin.equals(data);
                    case ">=":
                        return origin.compareTo(data) >= 0;
                    case "<=":
                        return origin.compareTo(data) <= 0;
                    case "!=":
                        return !origin.equals(data);
                }
//                if(tag.equals(">")){
//                    return origin > data;
//                }
//                if(tag.equals("<")){
//                    return origin < data;
//                }
//                if(tag.equals("=")){
//                    return origin.equals(data);
//                }
//                if(tag.equals(">=")){
//                    return origin >= data;
//                }
//                if(tag.equals("<=")){
//                    return origin <= data;
//                }
//                if(tag.equals("!=")){
//                    return !origin.equals(data);
//                }
                return false;
            }
            return false;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return false;
        }
    }

    // 获取判断，
    // 如果非法，则返回0
    public static boolean getEqualInteger(Integer origin,Integer data, String tag){
        try{
            if(origin != null && data != null){
                switch(tag){
                    case ">":
                        return origin > data;
                    case "<":
                        return origin < data;
                    case "=":
                        return origin.equals(data);
                    case ">=":
                        return origin >= data;
                    case "<=":
                        return origin <= data;
                    case "!=":
                        return !origin.equals(data);
                }
//                if(tag.equals(">")){
//                    return origin > data;
//                }
//                if(tag.equals("<")){
//                    return origin < data;
//                }
//                if(tag.equals("=")){
//                    return origin.equals(data);
//                }
//                if(tag.equals(">=")){
//                    return origin >= data;
//                }
//                if(tag.equals("<=")){
//                    return origin <= data;
//                }
//                if(tag.equals("!=")){
//                    return !origin.equals(data);
//                }
                return false;
            }
            return false;
        }catch (Exception e){
            System.out.println("获取数据错误");
            return false;
        }
    }

    // 获取判断，
    // 如果非法，则返回0
    public static Double getDevideDoubleInteger(Double origin,Integer data){
        try{
            if(origin != null && data != null && data != 0){
                return origin / data;
            }
            return null;
        }catch (Exception e){
            System.out.println("警告：获取数据错误");
            return null;
        }
    }

    // 获取范围内的随机数
    public static Double getRandomDataByRange(double min, double max, int decimal ){
        // 放大0(n次方)倍
        double step = Math.pow(10,decimal);
        // 范围长度
        double range = Math.floor((max - min)*step);
        // 获取一个范围内随机数据
        double index = Math.floor(Math.random() * range);
        // 得到最新的随机数据
        double data = (min + index / step);
        // 格式化数据后返回;
        return getDoubleFormat(data,decimal);
    }
    public static Integer getRandomDataByRange(Integer min, Integer max){
        return (int) (min + Math.random() * (max - min));
    }


    // 1.获取日范围数据
    public static Map<String, Object> getDayRange(String month) throws Exception {
        // 获取当前时间
        String startTime = month.substring(0,10) + " 00:00:00";
        String endTime = GlobalUtils.getDateAddDay(startTime,1);

        // 截止时间不能超过当前时间
        String res1 = GlobalUtils.getCompareDate(startTime);
        if(res1 != null){
            return null;
        }
        String res2 = GlobalUtils.getCompareDate(endTime);
        if(res2 != null){
            endTime = res2;
        }
//        // 新添加1秒的时间(保证一定能获取当前时间的数据)
//        endTime = endTime.substring(0,17) + "01";
        String finalEndTime = endTime;
        // 天数列表
        List<String> dates = dateUtils.findHours(startTime, endTime);
        return new HashMap<String, Object>(){{
            put("startTime",startTime);
            put("endTime", finalEndTime);
            put("dates", dates);
        }};

    }
    // 2.获取月范围数据
    public static Map<String, Object> getMonthRange(String month) throws Exception {
        // 获取当前时间
        String startTime = month.substring(0,7) + "-01 00:00:00";
        String endTime = GlobalUtils.getDateAddMonth(startTime,1);

        // 截止时间不能超过当前时间
        String res1 = GlobalUtils.getCompareDate(startTime);
        if(res1 != null){
            return null;
        }
        String res2 = GlobalUtils.getCompareDate(endTime);
        if(res2 != null){
            endTime = res2;
            // 如果是查询当前月份，则默认添加一天
            endTime = GlobalUtils.getDateAddDay(endTime,1);
            endTime = endTime.substring(0,11) + "00:00:00";
        }
//        // 新添加1秒的时间(保证一定能获取当前时间的数据)
//        endTime = endTime.substring(0,17) + "01";
        String finalEndTime = endTime;
        // 天数列表
        List<String> dates = dateUtils.findDays(startTime, endTime);
        return new HashMap<String, Object>(){{
            put("startTime",startTime);
            put("endTime", finalEndTime);
            put("dates", dates);
        }};

    }
    // 3.获取年范围数据
    public static Map<String, Object> getYearRange(String year) throws Exception {

        String startTime = year.substring(0,4) + "-01-01 00:00:00";
        String endTime = GlobalUtils.getDateAddYear(startTime,1);

        // 截止时间不能超过当前时间
        String res1 = GlobalUtils.getCompareDate(startTime);
        if(res1 != null){
            return null;
        }
        String res2 = GlobalUtils.getCompareDate(endTime);
        if(res2 != null){
            endTime = res2;
        }
        // 新添加1秒的时间(保证一定能获取当前时间的数据)
        endTime = endTime.substring(0,17) + "01";
        String finalEndTime = endTime;
        // 天数列表
        List<String> dates = dateUtils.findDays(startTime, endTime);
        return new HashMap<String, Object>(){{
            put("startTime",startTime);
            put("endTime", finalEndTime);
            put("dates", dates);
        }};
    }

    // 将结果中的字符串数组转换成数组
    public static String[] getStrArrayList(String data){
        try{
            if(data == null){
                return new String[0];
            }
            String b = data.replaceAll("[\\[|\\]|\"]","");
            return b.split("[,]");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return new String[0];
        }
    }

    // 获取当前类型
    public static String getType(Object data){
        String arr[] = data.getClass().getName().split("[.]");
        return arr[arr.length-1];
    }

    // 判断当前参数是否为空
    public static boolean isNotEmpty(Object data){
        try{
            if(data != null){
                String type = getType(data);
                if(getEqualString(type,"String","=") && ((String)data).length() > 0){
                    return true;
                }
                return false;
            }
            return false;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
    //判断参数是什么
    public static String parseTime(String time){
        //2022-01-01 00:00:00
        if (time.length() == 4) {
            return "年";
        } else if (time.length() == 7) {
            return "月";
        } else if (time.length() == 10) {
            return "日";
        } else if (time.length()==13) {
            return "时";
        } else if (time.length()==16) {
            return "分";
        }else if (time.length()==19) {
            return "秒";
        }else{
            System.err.println("请输入正确的日期格式");
            return "请输入正确的日期格式";
        }
    }
}
